import apiUrl from '@/utils/api_url.js';
import isokstokenServer from '@/utils/isokstokenServer.js';
import isokstoken from '@/utils/isokstoken';

class Ajax {
	constructor() {

	}
	getRequest(url, params) {
		return new Promise((resolve, reject) => {
			try {
				let key = 'mLZnRtDSPNfG7mqKyeQl0zkvzVEdasOd'
				let token_data = {
					key: key,
					cry: isokstokenServer
				}
				let token = isokstoken.getIsoksToken(token_data);
				uni.setStorageSync('token', token);
				uni.request({
					url: apiUrl.base_url + url,
					method: 'GET',
					header: {
						'Authorization': token,
						 'IsoksToken': token
					},
					data: params,
					success: res => {
						console.log(res)
						if (res.statusCode == 200) {
							resolve(res);
							return;
						}
						if (res.statusCode == 401) {
							uni.navigateTo({
								url: '/pages/login/login'
							})
							return;
						}
						uni.showToast({
							icon: 'none',
							title: res.data.msg
						})
					},
					fail: err => {
						reject(err)
					},
				});
			} catch (e) {
				console.log(e);
				//TODO handle the exception
			}

		})
	}

	postRequest(url, params) {
		return new Promise((resolve, reject) => {

			try {
				// const token = uni.getStorageSync('token');
				let key = 'mLZnRtDSPNfG7mqKyeQl0zkvzVEdasOd'
				let token_data = {
					key: key,
					cry: isokstokenServer
				}
				let token = isokstoken.getIsoksToken(token_data);
				uni.setStorageSync('token', token);
				uni.request({
					url: apiUrl.base_url + url,
					data: params,
					header: {
						'Authorization': token,
						 'IsoksToken': token
					},
					method: 'POST',
					success: res => {
						if (res.statusCode == 200) {
							resolve(res);
						}
						if (res.statusCode == 401) {
							uni.navigateTo({
								url: '/pages/login/login.vue'
							})
						}
						uni.showToast({
							icon: 'none',
							title: res.data.msg
						})
					},
					fail: err => {
						reject(err)
					},
				})
			} catch (e) {
				console.log(e)
			}

		})
	}
}


export default Ajax;
